﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.WebControls.WebParts;

namespace eVoting.Account
{
    public partial class Login : System.Web.UI.Page
    {
        DBManager db;
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "~/Account/Register.aspx";
            db = new DBManager();
            String s = ((String)Session["bool"]);
            if (s == "1")
            {
                lbl_login.Text = "<font color = #FF0000> Invalid username/password Combination </font>";
            }
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            string username = LoginUser.UserName;
            string password = LoginUser.Password;
            Console.WriteLine(username);
            Console.WriteLine(password);
            string salt = "";
            User user = null;
            try
            {
                user = db.getUserByMail(username);
                salt = user.pwSalt;
            }
            catch
            {
                Session["bool"] = "1";
                Response.Redirect("~/Account/Login.aspx");
            }

            string hashedPW = db.CreatePasswordHash(password, salt);

            if (hashedPW == user.password)
            {
                String userID = user.ID + "";
                Session["id"] = userID;
                if (!IsPwExpired(user))
                {
                    FormsAuthentication.RedirectFromLoginPage(user.firstName + " " + user.lastName, true);
                    Response.Redirect("~/Default.aspx");
                }
                else
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "javascript:alert('Your Password is expired. Please reset you Password' !');window.location = 'ResetPassword.aspx'", true);
                    Response.Redirect("~/Account/ResetPassword.aspx");
                }
            }
            else
            {
                Session["bool"] = "1";
                Response.Redirect("~/Account/Login.aspx");
            }
            int id = Int32.Parse((String)Session["id"]);
        }

        bool IsPwExpired(User user)
        {
            DateTime pwDate = user.pwDate;
            DateTime expiryDate = pwDate.AddMonths(3);

            if (DateTime.Now > expiryDate)
                return true;
            return false;
        }
    }
}
